/**
 * @file authSlice.js
 * @description 用户认证状态的 Redux slice。
 */
import { createSlice } from '@reduxjs/toolkit';

const getInitialAuthState = () => {
  try {
    const storedUser = localStorage.getItem('authUser');
    if (storedUser) {
      return { isAuthenticated: true, user: JSON.parse(storedUser) };
    }
  } catch (error) {
    console.error("无法从localStorage解析用户数据:", error);
  }
  return { isAuthenticated: false, user: null };
};

const initialState = getInitialAuthState();

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    loginSuccess: (state, action) => {
      state.isAuthenticated = true;
      state.user = action.payload;
      try {
        localStorage.setItem('authUser', JSON.stringify(action.payload));
      } catch (error) {
        console.error("无法向localStorage存储用户数据:", error);
      }
    },
    logout: (state) => {
      state.isAuthenticated = false;
      state.user = null;
      try {
        localStorage.removeItem('authUser');
      } catch (error) {
        console.error("无法从localStorage移除用户数据:", error);
      }
    },
    /**
     * 更新用户信息。
     * @param {object} state - 当前的 state。
     * @param {object} action - Redux action，action.payload 应该是包含更新后用户信息的对象。
     */
    updateUserProfile: (state, action) => {
      if (state.user && action.payload) {
        state.user = { ...state.user, ...action.payload }; // 合并旧用户信息和新信息
        try {
          localStorage.setItem('authUser', JSON.stringify(state.user));
        } catch (error) {
          console.error("无法向localStorage更新用户数据:", error);
        }
      }
    },
  },
});

export const { loginSuccess, logout, updateUserProfile } = authSlice.actions; // 添加 updateUserProfile
export default authSlice.reducer;